from io import BytesIO
from fastapi import APIRouter, Depends, Request, WebSocketDisconnect, status, WebSocket
from fastapi.responses import StreamingResponse
from typing import Optional, List, Any
from sqlmodel import Session, select
from schemas.common import RETURN, ListResponse, ListRequest
import json

from server.admin.SystemWebsoket import manager


router = APIRouter(tags=["大屏数据"])

@router.websocket("/ws/{token}")
async def websocket_endpoint(websocket: WebSocket, token: str):
    await manager.connect(websocket, token)
    try:
        while True:
            data = await websocket.receive_text()
            dataJson = json.loads(data)
            if dataJson["type"] == "ping":
                await manager.send_personal_message("pong", token)
            else:
                await manager.broadcast(f"User {token} says: {data}")

            # await manager.broadcast(f"User {token} says: {data}")
    except WebSocketDisconnect:
        await manager.disconnect(token)

@router.get("/ws/send/{token}")
async def send_message(token: str, message: str):
    await manager.send_personal_message(f"You wrote: {message}", token)
    await manager.broadcast(f"User {token} says: {message}")
    return {"message": "Sent"}